package mysql

import (
	"gorm.io/gorm"
	"shopping/logger"
	"shopping/model"
)

type OrderDao struct {
	db *gorm.DB
}

// NewOrderDao 实例化
func NewOrderDao(db *gorm.DB) *OrderDao {
	return &OrderDao{
		db: db,
	}
}

// 创建表
func (dao *OrderDao) Migration() {
	err := dao.db.AutoMigrate(&model.Order{})
	if err != nil {
		logger.Log.Error(err.Error())
	}
}

// FindByOrderId 根据订单id查找
func (dao *OrderDao) FindByOrderId(oid int64) (*model.Order, error) {
	var currentOrder *model.Order
	err := dao.db.Where("IsCanceled = ?", false).Where("id", oid).First(currentOrder).Error
	if err != nil {
		return nil, err
	}
	return currentOrder, err
}

// Update 更新订单
func (dao *OrderDao) Update(newOrder model.Order) error {
	err := dao.db.Save(&newOrder).Error
	if err != nil {
		return err
	}
	return nil
}

// Create 创建订单
func (dao *OrderDao) Create(ci *model.Order) error {
	return dao.db.Create(ci).Error
}

// GetAll 获取所有订单
func (dao *OrderDao) GetAll(pageIndex, pageSize int, uid int64) ([]model.Order, int) {
	var orders []model.Order
	var count int64

	dao.db.Where("IsCanceled = ?", 0).Where(
		"UserId = ?", uid).Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&orders).Count(&count)
	for i, order := range orders {
		dao.db.Where("OrderId = ?", order.Id).Find(&orders[i].OrderedItems)
		for j, item := range orders[i].OrderedItems {
			dao.db.Where("Id = ?", item.ProductId).First(&orders[i].OrderedItems[j].Product)
		}
	}
	return orders, int(count)
}
